import static java.lang.Thread.sleep;

class MyBlockingQueue {
    private String[] data = null;

    private int head;//指向第一个元素
    private int tail;//指向最后一个元素的下一个位置
    private int usedSize;


    public MyBlockingQueue(int capacity) {
        this.data = new String[capacity];
    }

    public void put(String str) throws InterruptedException {
        synchronized (this) {
            while (this.usedSize >= this.data.length) {
                this.wait();
            }

            this.data[this.tail++] = str;
            this.usedSize++;
            if (this.tail == this.data.length) {
                this.tail = 0;
            }

            this.notify();
        }
    }

    public String take() throws InterruptedException {
        synchronized (this) {
            while (this.usedSize == 0) {
                this.wait();
            }

            String ret = this.data[this.head++];
            if (this.head == this.data.length) {
                this.head = 0;
            }
            this.usedSize--;

            this.notify();

            return ret;
        }
    }
}

public class Demo3 {
    public static void main(String[] args) {
        MyBlockingQueue myBlockingQueue = new MyBlockingQueue(100);

        Thread thread1 = new Thread(() -> {
           for (int i = 0; i < 50000; i++) {
               try {
                   myBlockingQueue.put(i + " ");
                   System.out.println("生产元素 " + i);
//                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                try {
                    String elem = myBlockingQueue.take();
                    System.out.println("消费元素 " + elem);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        thread1.start();
        thread2.start();
    }
}
